package com.cwj;

import sun.nio.cs.ISO_8859_2;
import sun.nio.cs.US_ASCII;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenwujie
 * @date 2020/9/189:58
 */
public class Base64Test {
    public static void main(String[] args) throws UnsupportedEncodingException {
        BufferedImage image = new BufferedImage(40, 30, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();
        graphics.fillRect(0, 0, 40, 30);
        graphics.setColor(new Color(12, 32, 74));
        graphics.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
        graphics.drawString("p", 0, 25);
        graphics.dispose();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encode = encoder.encode(bytes);
        String base64Str = new String(encode);
        System.out.println("data:image/jpeg;base64," + base64Str);

    }

    /**
     * 图片二进制流转base64
     * @param bytes
     * @return
     */
    public String image2Base64(byte[] bytes){
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encode = encoder.encode(bytes);
        String base64Str = new String(encode);
        return "data:image/jpeg;base64," + base64Str;
    }
}